package zip;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

/**
 * @author jukg
 * @date 2023/07/28 17:27
 * @description
 */
public class GzTest {
    public static void main(String[] args) throws Exception {
        unGzipFile("C:\\Users\\Administrator\\Desktop\\curl.gz");
        //unGzipFile2("C:\\Users\\Administrator\\Desktop\\20230727_410000_pay_2.gz");
    }

    /**
     * 解压文件
     *
     * @param sourcedir 文件目录及文件名字
     */
    public static void unGzipFile(String sourcedir) {
        String ouputfile = "";
        try {
            //建立gzip压缩文件输入流
            FileInputStream fin = new FileInputStream(sourcedir);
            //建立gzip解压工作流
            GZIPInputStream gzin = new GZIPInputStream(fin);
            //建立解压文件输出流
            ouputfile = sourcedir.substring(0, sourcedir.lastIndexOf('.'));
//            ouputfile = ouputfile.substring(0,ouputfile.lastIndexOf('.'));
            FileOutputStream fout = new FileOutputStream(ouputfile);
            int num;
            byte[] buf = new byte[1024];

            while ((num = gzin.read(buf, 0, buf.length)) != -1) {
                fout.write(buf, 0, num);
            }
            gzin.close();
            fout.close();
            fin.close();
        } catch (Exception ex) {
            System.err.println(ex.toString());
        }
        return;

    }

    /**
     * 解压文件
     *
     * @param sourcedir 文件目录及文件名字
     */
    public static void unGzipFile2(String sourcedir) throws Exception {
        String ouputfile = "";
        GZIPInputStream gzin = null;
        FileOutputStream fout = null;
        FileInputStream fin = null;

        try {
            //建立gzip压缩文件输入流
            fin = new FileInputStream(sourcedir);
            //建立gzip解压工作流
            gzin = new GZIPInputStream(fin);
            //建立解压文件输出流
            ouputfile = sourcedir.substring(0, sourcedir.lastIndexOf('.'));
            fout = new FileOutputStream(ouputfile);
            int num;
            byte[] buf = new byte[1024];

            while ((num = gzin.read(buf, 0, buf.length)) != -1) {
                fout.write(buf, 0, num);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (gzin != null) {
                try {
                    gzin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (fout != null) {
                try {
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
